package com.lanou.hotel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lanou.hotel.entity.User;
import com.lanou.hotel.mapper.UserMapper;
import com.lanou.hotel.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lanou.hotel.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author msy
 * @since 2023-10-17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 验证登录信息
     * @param user
     * @return
     */
    @Override
    public ResultVO<Map<String, Object>> login(User user) {

        //先通过用户名去查询
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,user.getUsername());
        User tarUser = userMapper.selectOne(wrapper);

        //用户名不存在
        if (tarUser == null) {
            return ResultVO.failed("用户名不存在");
        }
        //密码是否正确
        if (!Objects.equals(tarUser.getPassword(),user.getPassword())) {
            return ResultVO.failed("密码错误");
        }

        //通过UUID获取key作为该用户token
        String token = "user:" + UUID.randomUUID().toString().replaceAll("-","");

        //将token作为key 对象作value存入redis中
        tarUser.setPassword(null);//清空密码
        redisTemplate.opsForValue().set(token,tarUser,30, TimeUnit.MINUTES);

        Map<String, Object> map = new HashMap<>();
        map.put("token",token);

        return ResultVO.success("登陆成功",map);
    }

    /**
     * 返回前端 info
     * @param token
     * @return
     */
    @Override
    public ResultVO<Map<String, Object>> info(String token) {

        //从redis中获取当前请求用户
        User user = (User) redisTemplate.opsForValue().get(token);

        //对redis中user的判空
        if (user == null) {
            return ResultVO.failed("token认证失败!");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("roles", "~~~");
        map.put("introduction", "I am a super administrator");
        map.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        map.put("name", "Super Admin");
        return ResultVO.success("登录成功",map);
    }

    /**
     * 清楚redis中的redis
     * @param token
     * @return
     */
    @Override
    public ResultVO logout(String token) {
        if (redisTemplate.delete(token)) {
            return ResultVO.success("注销成功",null );
        }else {
            return ResultVO.failed("注销失败");
        }
    }
}
